let fs = require('fs');
let path = require('path');
let router = require('koa-router')();

function searchControllers(defaultDir){
    let files = fs.readdirSync(defaultDir);

    let resultFiles = files.filter((fileName) => {
        return fileName.endsWith('.js') && fileName !== 'index.js';
    });

    return resultFiles;
}

function registerControllers(files,currPath){
    files.forEach(item=>{
        let temPath = path.join(currPath,item);
        let routerObj = require(temPath);

        for(let keys in routerObj){
                let type = routerObj[keys][0];
                let fn = routerObj[keys][1];

                if(type === 'get'){
                    router.get(keys,fn);
                }
                else{
                    router.post(keys,fn);    
                }
        }
    })
}    

module.exports = function(dir){
    let defaultDir=dir || '/controllers';
    let root = path.resolve('.');
    let resultControllerPath = path.join(root, defaultDir);
    let files=searchControllers(resultControllerPath);
    registerControllers(files,resultControllerPath);
    return router.routes();
};